#include "EventLoop.hpp"
#include "TcpServer.hpp"
#include "ThreadPool.h"
#include <iostream>
using std::cout;
using std::endl;


class Mytask{
public:
    Mytask(string msg, wd::TcpConnectionptr tcpconn)
    :_msg(msg)
    ,_tcpconn(tcpconn){

    }
    void process(){
        printf("in Mytask::process\n");
        _tcpconn->sendInLoop(_msg);
    }
private:
    string _msg;
    wd::TcpConnectionptr _tcpconn;
};

class EchoServer{
public:
    EchoServer(int threadnum,int que_len,int port, string ip)
    :_threadpool(threadnum,que_len)
    ,_tcpserver(port,ip)
    {
    }
    void start(){
        using namespace std::placeholders;
        _tcpserver.setAllCallbacks(
                                   std::bind(&EchoServer::onConnection,this,_1),
                                   std::bind(&EchoServer::onMessage,this,_1),
                                   std::bind(&EchoServer::onClose,this,_1));
        _threadpool.start();
        _tcpserver.start();
    }

    void stop(){
        _threadpool.stop();
        _threadpool.stop();
    }

private:
    void onConnection(wd::TcpConnectionptr tcpconn){
        printf("a new clienfd connected.\n");
    }
    
    void onMessage(wd::TcpConnectionptr tcpconn){
        string msg = tcpconn->receive();
        cout << "receive msg:"<< msg << endl;
    
        Mytask task(msg,tcpconn);
        _threadpool.addTask(std::bind(&Mytask::process,task));
        //tcpconn->send("receive your msg !");
    }
    
    void onClose(wd::TcpConnectionptr tcpconn){
        printf("a clienfd closed.\n");
    }

private:
    ThreadPool _threadpool;
    wd::TcpServer _tcpserver;
};




    

int main()
{
    EchoServer server(4,10,12345,"0.0.0.0");
    server.start();

    return 0;
}

